package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.device.domain.PowerBank;
import com.share.device.mapper.PowerBankMapper;
import com.share.device.service.IPowerBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank>
        implements IPowerBankService
{
    @Autowired
    private PowerBankMapper powerBankMapper;

    /**
     * 查询充电宝列表
     * @param powerBank
     * @return
     */
    @Override
    public List<PowerBank> selectPowerBankList(PowerBank powerBank)
    {
        return powerBankMapper.selectPowerBankList(powerBank);
    }

    /**
     * 新增充电宝
     * @param powerBank
     * @return
     */
    @Override
    public int savePowerBank(PowerBank powerBank) {
        //判断powerBankNo是否已经存在，如果不存在才添加
        String powerBankNo = powerBank.getPowerBankNo();
        //封装条件
        LambdaQueryWrapper<PowerBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PowerBank::getPowerBankNo,powerBankNo);
        Long count = powerBankMapper.selectCount(wrapper);
        if (count > 0) {
            throw new ServiceException("该充电宝编号已存在");
        }
        int rows = powerBankMapper.insert(powerBank);
        return rows;
    }

    @Override
    public int updatePowerBank(PowerBank powerBank) {
        //判断充电宝状态值为0才修改
        Long id = powerBank.getId();
        PowerBank oldPowerBank = powerBankMapper.selectById(id);
        if (oldPowerBank != null && "0".equals(oldPowerBank.getStatus())) {

            int rows = powerBankMapper.updateById(powerBank);
            return  rows;

        }
        return 0;
    }

    @Override
    public PowerBank getByPowerBankNo(String powerBankNo) {
        LambdaQueryWrapper<PowerBank> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<PowerBank> eq = wrapper.eq(PowerBank::getPowerBankNo, powerBankNo);
        return powerBankMapper.selectOne(eq);
    }

}